//
//  WXApiManager.m
//  SDKSample
//
//  Created by Jeason on 16/07/2015.
//
//

#import "WXApiManager.h"

@implementation WXApiManager

#pragma mark - LifeCycle
+(instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static WXApiManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[WXApiManager alloc] init];
    });
    return instance;
}


#pragma mark - WXApiDelegate

#pragma mark -----------------微信支付回掉-----------------
-(void) onReq:(BaseReq*)req{
    
}

-(void) onResp:(BaseResp*)resp{
    if([resp isKindOfClass:[PayResp class]]){
        if (resp.errCode == WXSuccess) {
            if ([self.delegate respondsToSelector:@selector(wxPayRespSuccess)]) {
                [self.delegate wxPayRespSuccess];
            }
        }else{
            if ([self.delegate respondsToSelector:@selector(wxPayRespError)]) {
                [self.delegate wxPayRespError];
            }
            
        }
    }
}

-(void)wxPaySdk:(NSString *)payMessage{

    
//    payMessage = @"{\"appId\":\"wx7fe601695e9ef672\",\"partnerId\":\"1320144701\",\"prepayId\":\"wx20160321171028bde353d8160642024137\",\"nonceStr\":\"pbibufa5w843brjwbooq\",\"timeStamp\":\"1458580264\",\"packageValue\":\"Sign=WXPay\",\"sign\":\"9e3afa54d6eb2b0653e1fbfa95afd130\"}";
    NSDictionary *payMessageDic = [payMessage objectFromJSONString];
    
    //向微信注册
    [WXApi registerApp:[payMessageDic objectForKey:@"appId"] withDescription:@"bus"];
    //调起微信支付
    PayReq* req             = [[PayReq alloc] init];
    req.openID              = [payMessageDic objectForKey:@"appId"];
    req.partnerId           = [payMessageDic objectForKey:@"partnerId"];
    req.prepayId            = [payMessageDic objectForKey:@"prepayId"];
    req.nonceStr            = [payMessageDic objectForKey:@"nonceStr"];
    req.timeStamp           = [[payMessageDic objectForKey:@"timeStamp"]  intValue];
    req.package             = [payMessageDic objectForKey:@"packageValue"];
    req.sign                = [payMessageDic objectForKey:@"sign"];
    
    if (![WXApi sendReq:req]) {
        [self showTipViewWithMessage:@"请先安装微信客户端"];
    }
}


// 提示框
-(void)showTipViewWithMessage:(NSString *)message{
    
    [[[UIAlertView alloc ] initWithTitle:@""
                                 message:message
                                delegate:nil
                       cancelButtonTitle:@"确定"
                       otherButtonTitles:nil, nil]  show];
}

@end
